// 获取app实例
const app = getApp();

Page({
  data: {
    // 从接口获取的题库数据
    showmsg: false,
    type: '',
    massges: "",
    questionBank: [],
    showJiucuoModal: false,
    currentQuestionIndex: 0,
    selectedOptions: {}, // 存储每个题目的选择答案 {questionIndex: optionId}
    answeredStatus: {}, // 存储每个题目的答题状态 {questionIndex: true/false}
    correctStatus: {}, // 存储每个题目的正确状态 {questionIndex: true/false}
    selectedClass: {}, // 存储每个题目的选项样式类 {questionIndex: [class1, class2, ...]}
    countdownSeconds: 0,
    totalHeaderHeightall: "",
    totalQuestions: 0,
    manualDrag: false, // 记录用户是否手动拖动了swiper
    countdownTimer: null, // 计时器引用，用于清除计时器
    // AI问答相关数据
    messages: [],
    isLoading: false,
    isFirstQuestion: true,
    questionId: '', // 题目ID
    nowquestionuseranswer: "",
    nowquestionuseranswerarray: [],
    showAiAnalysis: false, // 控制是否显示AI解析
    jiucuoRecords: {}, // 存储已纠错的题目记录
    // 答题结果相关数据
    showResultModal: false, // 控制是否显示成绩弹窗
    activityResult: null // 存储用户答题结果数据
  },

  onLoad: function (options) {
    // 页面加载时获取自定义头部高度
    this.queryHeaderHeight();
    // 从本地缓存读取已纠错的题目记录
    this.loadJiucuoRecords();
    // 检查用户是否已经答过题
    this.checkActivityResult();
    // 加载活动问题列表
    this.loadActivityQuestions();
  },

  // 从本地缓存加载已纠错的题目记录
  loadJiucuoRecords: function () {
    try {
      const jiucuoRecords = wx.getStorageSync('jiucuo_records') || {};
      this.setData({
        jiucuoRecords: jiucuoRecords
      });
      console.log('已加载纠错记录:', jiucuoRecords);
    } catch (e) {
      console.error('读取纠错记录失败:', e);
    }
  },

  /**
   * 更新选项样式类/**
   * 更新选项的选中样式类
   */
  updateSelectedClass: function (selectedOption, userSelectedOptions, userAnswer, isAnswered, questionTypeCode, options, correctAnswer) {
    const optionsCount = options ? options.length : 0;
    const selectedClass = [];

    // 优先使用从答题记录合并过来的用户答案
    if (userAnswer && isAnswered) {
      for (let i = 0; i < optionsCount; i++) {
        const optionKey = String.fromCharCode(65 + i); // A, B, C, D...

        if (questionTypeCode === 1) {
          // 单选题：用户答案等于选项key
          selectedClass.push(userAnswer === optionKey ? 'selected' : '');
        } else if (questionTypeCode === 2) {
          // 多选题：用户答案包含选项key（将userAnswer转换为数组判断）
          const userAnswerArray = userAnswer.split(',');
          // 已答题状态下，返回correct或wrong样式类
          if (userAnswerArray.includes(optionKey)) {
            // 用户选择了这个选项，判断是否正确
            const correctAnswerArray = correctAnswer ? correctAnswer.split(',') : [];
            selectedClass.push(correctAnswerArray.includes(optionKey) ? 'correct' : 'wrong');
          } else {
            // 用户没有选择这个选项，判断是否是正确答案
            const correctAnswerArray = correctAnswer ? correctAnswer.split(',') : [];
            selectedClass.push(correctAnswerArray.includes(optionKey) ? 'correct' : '');
          }
        } else if (questionTypeCode === 3) {
          // 判断题：用户答案是"正确"或"错误"
          const booleanMapping = { 0: '正确', 1: '错误' };
          selectedClass.push(userAnswer === booleanMapping[i] ? 'selected' : '');
        } else {
          selectedClass.push('');
        }
      }
    } else {
      // 没有用户答案时使用当前选中状态
      for (let i = 0; i < optionsCount; i++) {
        const optionKey = String.fromCharCode(65 + i); // A, B, C, D...

        if (questionTypeCode === 1 || questionTypeCode === 3) {
          // 单选题和判断题逻辑相同
          selectedClass.push(i === selectedOption ? 'selected' : '');
        } else if (questionTypeCode === 2) {
          // 多选题逻辑：检查选项ID是否在用户选择的选项中
          selectedClass.push(userSelectedOptions && userSelectedOptions.indexOf(optionKey) > -1 ? 'multiple-selected' : '');
        } else {
          selectedClass.push('');
        }
      }
    }

    return selectedClass;
  },

  /**
   * 检查用户活动答题结果
   * 如果用户已经答过题，显示不可关闭的成绩弹窗
   */
  checkActivityResult: function () {
    // 从缓存获取活动ID
    const activityId = wx.getStorageSync('current_activity_id') || 1;

    app.api.getActivityResult({ activity_id: activityId })
      .then(res => {
        console.log('检查答题结果:', res);

        if (res.data && res.data.id) {
          // 计算正确率
          const resultData = res.data;
          if (resultData.total_questions > 0) {
            resultData.correct_rate = Math.round((resultData.correct_count / resultData.total_questions) * 100);
          } else {
            resultData.correct_rate = 0;
          }

          // 计算平均分和最高分（如果有多次尝试）
          let avgScore = 0;
          let maxScore = 0;
          if (res.data.results && res.data.results.length > 0) {
            let totalScore = 0;
            for (let i = 0; i < res.data.results.length; i++) {
              const score = res.data.results[i].score || 0;
              totalScore += score;
              if (score > maxScore) {
                maxScore = score;
              }
            }
            avgScore = Math.round(totalScore / res.data.results.length);
          } else {
            maxScore = resultData.score || 0;
          }

          // 用户已经答过题，显示成绩弹窗
          this.setData({
            showResultModal: true,
            activityResult: resultData,
            activityResults: res.data.results || [],
            attemptCount: res.data.attempt_count || 0,
            remainingAttempts: res.data.remaining_attempts || 2,
            hasReachedMaxAttempts: res.data.has_reached_max_attempts || false,
            hasParticipated: res.data.attempt_count > 0,
            avgScore: avgScore,
            maxScore: maxScore
          });
        } else {
          // 用户未答题，保持现有逻辑
          console.log('用户未答题，继续正常流程');
        }
      })
      .catch(err => {
        console.error('检查答题结果失败:', err);
        // 接口调用失败时，继续正常流程
      });
  },

  /**
   * 加载活动问题列表
   * 调用frontend/activity/question/list接口获取活动ID为1的问题列表
   */
  loadActivityQuestions: function () {
    wx.showLoading({
      title: '加载题目中...',
      mask: true
    });

    app.api.getActivityQuestionList({ activity_id: 1 })
      .then(res => {
        wx.hideLoading();
        console.log('活动问题列表数据:', res);

        if (res.data && res.data.list && res.data.list.length > 0) {
          let lists = res.data.list.sort((a, b) => a.id - b.id)
          // 转换API返回的数据格式为页面需要的格式
          let options = [];
          const formattedQuestions = lists.map(q => {

            let questionType = q.question_type || 1; // 默认单选题

            if (questionType === 1) { // 单选题
              // 处理单选题选项
              if (q.options && Array.isArray(q.options)) {
                options = q.options.map((option, index) => {
                  // 选项标识：A, B, C, D...
                  const optionId = String.fromCharCode(65 + index);
                  return {
                    id: optionId,
                    content: option
                  };
                });
              }
            } else if (questionType === 2) { // 多选题
              // 处理多选题选项
              if (q.options && Array.isArray(q.options)) {
                options = q.options.map((option, index) => {
                  // 提取选项ID（字母部分）
                  const match = option.match(/^([A-Z])\./);
                  const optionId = match ? match[1] : String.fromCharCode(65 + index);
                  // 提取选项内容（去除字母和点）
                  const content = match ? option.substring(match[0].length) : option;
                  return {
                    id: optionId,
                    content: content
                  };
                });
              }
            } else if (questionType === 3) { // 判断题
              // 处理判断题选项
              if (q.options && Array.isArray(q.options)) {
                options = q.options.map((option, index) => {
                  const optionId = index === 0 ? '正确' : '错误';
                  return {
                    id: optionId,
                    content: option
                  };
                });
              }
            }

            return {
              id: q.id,
              content: q.question_name,
              options: options,
              correctAnswer: q.right_key,
              analysis: q.analysis, // 保存解析信息，用于后续显示
              questionType: questionType // 保存题型
            };
          });

          this.setData({
            questionBank: formattedQuestions,
            totalQuestions: res.data.total || formattedQuestions.length
          });

          // 加载第一题
          this.loadQuestion(0);
        } else {
          wx.showToast({
            title: '暂无题目数据',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('获取活动问题列表失败:', err);
        wx.showToast({
          title: '题目加载失败，请重试',
          icon: 'none'
        });
      });
  },

  // 加载指定索引的题目
  loadQuestion: function (index) {
    const questionBank = this.data.questionBank;

    // 检查题库是否为空或索引是否越界
    if (!questionBank || questionBank.length === 0) {
      console.warn('题库数据为空');
      return;
    }

    if (index >= questionBank.length) {
      console.warn('题目索引越界');
      return;
    }

    this.setData({
      currentQuestionIndex: index
    });
  },

  // swiper切换事件处理
  onSwiperChange: function (e) {
    const newIndex = e.detail.current;

    // 清除计时器，停止自动切换
    if (this.data.countdownTimer) {
      clearInterval(this.data.countdownTimer);
      this.setData({
        countdownTimer: null,
        countdownSeconds: 0 // 重置倒计时秒数
      });
    }

    // 切换题目后清空AI相关变量
    this.setData({
      currentQuestionIndex: newIndex,
      manualDrag: true, // 标记为用户手动拖动
      // 清空AI相关变量
      messages: [],
      isFirstQuestion: true, // 重置为第一题状态
      questionId: '',
      showAiAnalysis: false // 隐藏AI分析弹窗
    });
  },

  queryHeaderHeight: function () {
    // 查询自定义头部组件的高度
    const query = wx.createSelectorQuery();
    query.select('#customHeader').boundingClientRect();
    query.exec((res) => {
      if (res && res[0]) {
        this.setData({
          totalHeaderHeightall: res[0].height
        });
      }
    });
  },
  tijiao(e) {
    // 获取当前题目索引
    const questionIndex = this.data.currentQuestionIndex;
    const currentQuestion = this.data.questionBank[questionIndex];

    // 判断用户是否选择了选项
    if (!this.data.nowquestionuseranswerarray || this.data.nowquestionuseranswerarray.length === 0) {
      wx.showToast({
        title: '请至少选择一个选项',
        icon: 'none'
      });
      return;
    }

    // 排序和去重（虽然在selectOptionduoxuan中已经避免了重复，但这里再确保一下）
    const uniqueOptions = [...new Set(this.data.nowquestionuseranswerarray)];
    const newstarings = uniqueOptions.sort().join(',');

    // 获取正确答案
    const correctAnswer = currentQuestion.correctAnswer;

    // 判断是否正确
    const isCorrect = newstarings === correctAnswer;

    // 标记为已回答
    const newAnsweredStatus = { ...this.data.answeredStatus };
    const newCorrectStatus = { ...this.data.correctStatus };
    newAnsweredStatus[questionIndex] = true;
    newCorrectStatus[questionIndex] = isCorrect;

    this.setData({
      answeredStatus: newAnsweredStatus,
      correctStatus: newCorrectStatus
    });
  },
  // 多选题选择选项
  selectOptionduoxuan: function (e) {
    const optionId = e.currentTarget.dataset.id;
    const questionIndex = e.currentTarget.dataset.questionIndex;

    // 检查当前题目是否已回答
    if (this.data.answeredStatus && this.data.answeredStatus[questionIndex] === true) {
      // 题目已回答，不允许再次选择
      return;
    }

    // 创建新对象而不是修改现有对象，避免引用传递问题
    const newSelectedOptions = { ...this.data.selectedOptions };
    const newSelectedClass = { ...this.data.selectedClass };

    // 初始化当前题目的选项数组
    if (!newSelectedOptions[questionIndex]) {
      newSelectedOptions[questionIndex] = [];
    }

    // 切换选项的选中状态
    const optionIndex = newSelectedOptions[questionIndex].indexOf(optionId);
    if (optionIndex > -1) {
      // 取消选择
      newSelectedOptions[questionIndex].splice(optionIndex, 1);
    } else {
      // 添加选择
      newSelectedOptions[questionIndex].push(optionId);
    }

    // 排序选中的选项，确保与正确答案格式一致
    newSelectedOptions[questionIndex].sort();

    // 更新样式类
    const currentQuestion = this.data.questionBank[questionIndex];
    if (currentQuestion && currentQuestion.options) {
      // 直接传递选项ID数组，不再转换为索引
      newSelectedClass[questionIndex] = this.updateSelectedClass(
        null,
        newSelectedOptions[questionIndex],
        null,
        false,
        currentQuestion.questionType || 2,
        currentQuestion.options,
        currentQuestion.correctAnswer
      );
    }

    console.log('多选题选择:', newSelectedOptions[questionIndex]);

    // 更新数据
    this.setData({
      selectedOptions: newSelectedOptions,
      selectedClass: newSelectedClass,
      manualDrag: false
    });
  },

  // 选择选项
  selectOption: function (e) {
    const optionId = e.currentTarget.dataset.id;
    const questionIndex = e.currentTarget.dataset.questionIndex;

    // 检查当前题目是否已回答
    if (this.data.answeredStatus && this.data.answeredStatus[questionIndex] === true) {
      // 题目已回答，不允许再次选择
      return;
    }

    // 获取当前题目信息
    const currentQuestion = this.data.questionBank[questionIndex];
    const questionType = currentQuestion.questionType || 1;

    // 创建新对象而不是修改现有对象，避免引用传递问题
    const newSelectedOptions = { ...this.data.selectedOptions };
    const newAnsweredStatus = { ...this.data.answeredStatus };
    const newCorrectStatus = { ...this.data.correctStatus };
    const newSelectedClass = { ...this.data.selectedClass };

    let isCorrect = false;

    if (questionType === 2) { // 多选题
      // 对于多选题，使用数组存储选择的选项
      if (!newSelectedOptions[questionIndex]) {
        newSelectedOptions[questionIndex] = [];
      }

      // 切换选项的选中状态
      const optionIndex = newSelectedOptions[questionIndex].indexOf(optionId);
      if (optionIndex > -1) {
        // 取消选择
        newSelectedOptions[questionIndex].splice(optionIndex, 1);
      } else {
        // 添加选择
        newSelectedOptions[questionIndex].push(optionId);
      }

      // 排序选中的选项，确保与正确答案格式一致
      newSelectedOptions[questionIndex].sort();

      // 更新样式类
      if (currentQuestion && currentQuestion.options) {
        // 直接传递选项ID数组，不再转换为索引
        newSelectedClass[questionIndex] = this.updateSelectedClass(
          null,
          newSelectedOptions[questionIndex],
          null,
          false,
          currentQuestion.questionType || 2,
          currentQuestion.options,
          currentQuestion.correctAnswer
        );
      }

      // 多选题不需要立即判断正确与否，让用户可以继续选择
      return this.setData({
        selectedOptions: newSelectedOptions,
        selectedClass: newSelectedClass,
        manualDrag: false
      });
    } else if (questionType === 3) { // 判断题
      // 判断题直接判断是否正确
      newSelectedOptions[questionIndex] = optionId;
      isCorrect = optionId === currentQuestion.correctAnswer;

      // 标记为已回答
      newAnsweredStatus[questionIndex] = true;
      newCorrectStatus[questionIndex] = isCorrect;
    } else { // 单选题
      // 获取当前题目的正确答案
      newSelectedOptions[questionIndex] = optionId;
      isCorrect = optionId === currentQuestion.correctAnswer;

      // 标记为已回答
      newAnsweredStatus[questionIndex] = true;
      newCorrectStatus[questionIndex] = isCorrect;
    }

    // 使用新对象更新数据，并重置manualDrag标志
    this.setData({
      selectedOptions: newSelectedOptions,
      answeredStatus: newAnsweredStatus,
      correctStatus: newCorrectStatus,
      manualDrag: false // 重置手动拖动标志，确保答题后自动计时器能工作
    });

    // 对于单选题和判断题，正确后自动跳转
    if (questionType !== 2 && questionIndex === this.data.currentQuestionIndex && isCorrect) {
      // 如果不是最后一题，延迟一秒后自动跳转到下一题
      if (this.data.currentQuestionIndex < this.data.questionBank.length - 1) {
        setTimeout(() => {
          this.nextQuestion();
        }, 1000);
      }
    }
    // // 只有当前显示的题目才开始倒计时
    // if (questionIndex === this.data.currentQuestionIndex) {
    //   this.startCountdown();
    // }
  },

  // 开始倒计时
  startCountdown: function () {
    // 清除可能存在的旧计时器
    if (this.data.countdownTimer) {
      clearInterval(this.data.countdownTimer);
    }

    // 直接启动倒计时，manualDrag已在selectOption中重置
    this.setData({ countdownSeconds: 2 });

    // 创建新计时器并保存引用
    const timer = setInterval(() => {
      let seconds = this.data.countdownSeconds - 1;
      if (seconds <= 0) {
        clearInterval(timer);
        this.setData({ countdownTimer: null });
        this.nextQuestion();
      } else {
        this.setData({ countdownSeconds: seconds });
      }
    }, 1000);

    // 保存计时器引用到data中
    this.setData({ countdownTimer: timer });
  },

  // 下一题
  nextQuestion: function () {
    const currentIndex = this.data.currentQuestionIndex;
    const currentQuestion = this.data.questionBank[currentIndex];
    const questionType = currentQuestion ? currentQuestion.questionType || 1 : 1;

    // 对于多选题，需要在切换前检查并标记答案
    if (questionType === 2 && currentQuestion) {
      // 获取用户选择的选项
      const selectedOptions = this.data.selectedOptions[currentIndex] || [];

      // 只有当用户选择了选项才判断
      if (selectedOptions.length > 0 && !this.data.answeredStatus[currentIndex]) {
        // 排序选中的选项，确保与正确答案格式一致
        selectedOptions.sort();

        // 转换正确答案为数组并排序
        const correctAnswers = currentQuestion.correctAnswer.split(',').sort();

        // 判断是否所有选项都正确且数量一致
        let isCorrect = true;
        if (selectedOptions.length === correctAnswers.length) {
          for (let i = 0; i < selectedOptions.length; i++) {
            if (selectedOptions[i] !== correctAnswers[i]) {
              isCorrect = false;
              break;
            }
          }
        } else {
          isCorrect = false;
        }

        // 标记为已回答
        const newAnsweredStatus = { ...this.data.answeredStatus };
        const newCorrectStatus = { ...this.data.correctStatus };
        const newSelectedClass = { ...this.data.selectedClass };
        newAnsweredStatus[currentIndex] = true;
        newCorrectStatus[currentIndex] = isCorrect;

        // 更新答题后的样式类
        if (currentQuestion && currentQuestion.options) {
          // 将选项ID转换为索引（A->0, B->1, C->2, ...）
          const selectedIndexes = selectedOptions.map(opt => {
            return opt.charCodeAt(0) - 65; // A=65, B=66, ...
          });

          newSelectedClass[currentIndex] = this.updateSelectedClass(
            null,
            selectedIndexes,
            selectedOptions.join(','), // 用户答案
            true, // 已答题
            currentQuestion.questionType || 2,
            currentQuestion.options,
            currentQuestion.correctAnswer
          );
        }

        this.setData({
          answeredStatus: newAnsweredStatus,
          correctStatus: newCorrectStatus,
          selectedClass: newSelectedClass
        });
      }
    }

    const nextIndex = currentIndex + 1;
    if (nextIndex < this.data.questionBank.length) {
      // 直接通过swiper的current属性切换题目
      this.setData({
        currentQuestionIndex: nextIndex,
        manualDrag: false // 重置手动拖动标志，准备下一题
      });
    } else {
      // 所有题目都答完了
      const totalQuestions = this.data.totalQuestions;
      const content = totalQuestions > 0
        ? `恭喜你完成了所有${totalQuestions}道题目！`
        : '恭喜你完成了所有题目！';

      wx.showModal({
        title: '答题完成',
        content: content,
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            // 可以返回上一页或重新开始
            wx.navigateBack();
          }
        }
      });
    }
  },

  // 打开AI问答功能
  openAiChat: function () {
    const currentQuestion = this.data.questionBank[this.data.currentQuestionIndex];
    if (!currentQuestion || !currentQuestion.content) {
      wx.showToast({
        title: '题目信息加载中',
        icon: 'none'
      });
      return;
    }

    const message = "解析下这个题目：" + currentQuestion.content;

    // 重置消息列表，只保留当前解析
    this.setData({
      messages: [],
      showAiAnalysis: true
    });

    this.setData({
      isLoading: true,
      questionId: currentQuestion.id || ''
    });

    // 添加用户消息
    const userMessage = {
      type: 'user',
      content: message,
      time: this.formatTime(new Date())
    };

    this.setData({
      messages: [...this.data.messages, userMessage]
    }, () => {
      // 滚动到底部显示用户消息
      this.scrollToBottom();

      // 保存当前对话到localStorage
      this.saveCurrentAIChatMessages();
    });

    // 调用AI问答接口
    this.callAIChat(message);
  },

  // 打开纠错弹窗
  openJiucuoModal: function (e) {
    this.setData({
      questionId: e.currentTarget.dataset.id,
      showJiucuoModal: true
    });
  },

  // 答题完了算分数
  overs: function () {
    const { correctStatus, totalQuestions, questionBank, selectedOptions, answeredStatus } = this.data;

    // 统计正确的题目数量
    let correctCount = 0;

    // 先检查并处理所有未标记的多选题
    questionBank.forEach((question, index) => {
      if (question.questionType === 2 && !answeredStatus[index]) {
        const selected = selectedOptions[index] || [];
        if (selected.length > 0) {
          // 排序选中的选项
          selected.sort();
          // 转换正确答案为数组并排序
          const correctAnswers = question.correctAnswer.split(',').sort();

          // 判断是否所有选项都正确且数量一致
          let isCorrect = true;
          if (selected.length === correctAnswers.length) {
            for (let i = 0; i < selected.length; i++) {
              if (selected[i] !== correctAnswers[i]) {
                isCorrect = false;
                break;
              }
            }
          } else {
            isCorrect = false;
          }

          // 更新状态
          correctStatus[index] = isCorrect;
          answeredStatus[index] = true;
        }
      }
    });

    // 统计正确的题目数量
    Object.keys(correctStatus).forEach(index => {
      if (correctStatus[index]) {
        correctCount++;
      }
    });

    // 计算100分制的分数
    const score = totalQuestions > 0 ? Math.round((correctCount / totalQuestions) * 100) : 0;

    console.log('答题完成！正确题目数：', correctCount, '总分：', score);

    // 保存当前活动ID到缓存（这里使用固定的活动ID为1，后续可以根据实际需求修改）
    wx.setStorageSync('currentActivityId', 1);

    // 跳转到结果页面，带上分数数据
    wx.redirectTo({
      url: `/service/answerresult/answerresult?score=${score}&correctCount=${correctCount}&totalQuestions=${totalQuestions}`
    });

    return score;
  },
  // 关闭纠错弹窗
  closeJiucuoModal: function () {
    this.setData({
      showJiucuoModal: false
    });
  },
  handleJiucuoSubmit: function (e) {
    // 从组件传递的数据中获取内容和错误类型
    const content = e.detail && e.detail.content ? e.detail.content : this.data.feedbackContent;
    const errorType = e.detail && e.detail.errorType ? e.detail.errorType : '其他';

    // if (!content) {
    //   wx.showToast({
    //     title: '请输入纠错内容',
    //     icon: 'none'
    //   });
    //   return;
    // }

    const jiucuoRecords = wx.getStorageSync('jiucuo_records') || [];
    jiucuoRecords.push({
      questionId: this.data.questionId,
      content: content,
      error_type: errorType  // API期望下划线命名
    });
    wx.setStorageSync('jiucuo_records', jiucuoRecords);

    wx.showToast({
      title: '提交成功',
      icon: 'success'
    });
    // 清空内容并关闭弹窗
    this.setData({
      feedbackContent: '',
      showJiucuoModal: false
    });
    return
    const that = this;
    app.api.submitFeedback({
      questionId: this.data.questionId,
      content: content,
      error_type: errorType  // API期望下划线命名
    }).then(res => {
      wx.showToast({
        title: '提交成功',
        icon: 'success'
      });
      // 清空内容并关闭弹窗
      that.setData({
        feedbackContent: '',
        showJiucuoModal: false
      });
    }).catch(err => {
      console.error('提交纠错失败:', err);
      wx.showToast({
        title: '提交失败，请重试',
        icon: 'none'
      });
    });
  },
  /**
   * 调用AI问答接口
   */
  callAIChat: function (message) {
    const that = this;

    // 创建AI消息对象（用于流式传输）- 直接显示"正在思考中..."
    const aiMessage = {
      type: 'ai',
      content: '正在思考中...',
      parsedContent: '正在思考中...',
      time: that.formatTime(new Date()),
      isStreaming: true // 标记为流式传输中
    };

    // 先将AI消息添加到消息列表
    that.setData({
      messages: [...that.data.messages, aiMessage]
    }, () => {
      // 滚动到底部
      that.scrollToBottom();
    });

    const app = getApp();
    wx.request({
      url: app.globalData.baseUrl + '/frontend/ai/chat',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('userToken') || ''
      },
      timeout: 60000, // 设置60秒超时时间
      data: {
        message: message,
        questionId: this.data.questionId,
        isFirstQuestion: this.data.isFirstQuestion ? 1 : 0,
        stream: 1, // 启用流式传输
        isActivity: 1 // 标记为活动页面调用
      },
      success: function (res) {
        if (res.data.code === 200) {
          // 模拟流式效果：逐字显示内容
          const fullContent = res.data.data.content || '';
          const messages = that.data.messages;
          const lastIndex = messages.length - 1;

          // 延迟一小段时间后开始显示真实内容（让用户看到"正在思考中..."）
          setTimeout(() => {
            // 模拟逐字显示效果
            let currentIndex = 0;
            const typingInterval = setInterval(() => {
              if (currentIndex < fullContent.length) {
                const currentContent = fullContent.substring(0, currentIndex + 1);
                messages[lastIndex] = {
                  ...messages[lastIndex],
                  content: currentContent,
                  parsedContent: that.parseMarkdown(currentContent)
                };

                that.setData({
                  messages: messages
                }, () => {
                  that.scrollToBottom();
                });

                currentIndex++;
              } else {
                clearInterval(typingInterval);

                // 流式传输完成
                messages[lastIndex] = {
                  ...messages[lastIndex],
                  isStreaming: false
                };

                that.setData({
                  messages: messages,
                  isLoading: false,
                  isFirstQuestion: false
                }, () => {
                  // 保存当前对话到localStorage
                  that.saveCurrentAIChatMessages();
                });
              }
            }, 30); // 每30ms显示一个字符
          }, 500);
        } else {
          // 处理错误情况
          const messages = that.data.messages;
          messages[messages.length - 1] = {
            ...messages[messages.length - 1],
            content: res.data.message || '服务器错误，请稍后重试',
            parsedContent: res.data.message || '服务器错误，请稍后重试',
            isStreaming: false
          };

          that.setData({
            messages: messages,
            isLoading: false
          });
        }
      },
      fail: function (error) {
        console.error('AI聊天请求失败:', error);

        const messages = that.data.messages;
        messages[messages.length - 1] = {
          ...messages[messages.length - 1],
          content: '网络错误，请检查网络连接后重试',
          parsedContent: '网络错误，请检查网络连接后重试',
          isStreaming: false
        };

        that.setData({
          messages: messages,
          isLoading: false
        });
      }
    });
  },

  /**
   * 滚动到AI分析区域
   */
  scrollToBottom: function (forceScroll = false) {
    // 只有当AI分析区域可见时才执行滚动
    if (this.data.showAiAnalysis) {
      // 避免在流式传输过程中频繁滚动页面
      // 只在初始显示或强制滚动时执行
      const lastMessage = this.data.messages[this.data.messages.length - 1];
      if (forceScroll || !lastMessage || !lastMessage.isStreaming) {
        setTimeout(() => {
          // 查找消息列表容器而不是整个AI分析区域
          wx.createSelectorQuery().select('.ai-message-list').boundingClientRect(function (rect) {
            if (rect) {
              // 滚动到AI消息列表容器的顶部位置
              wx.pageScrollTo({
                scrollTop: rect.top - 100, // 减去100px作为顶部安全距离
                duration: 100 // 减少滚动时长，减轻闪烁
              });
            }
          }).exec();
        }, 50); // 减少延迟时间
      }
    }
  },

  /**
   * 解析Markdown格式
   */
  parseMarkdown: function (text) {
    // 简单的Markdown解析，根据需要扩展
    if (!text) return '';

    // 替换标题
    text = text.replace(/^### (.*$)/gm, '<h3>$1</h3>');
    text = text.replace(/^## (.*$)/gm, '<h2>$1</h2>');
    text = text.replace(/^# (.*$)/gm, '<h1>$1</h1>');

    // 替换加粗
    text = text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');

    // 替换换行
    text = text.replace(/\n/g, '<br/>');

    return text;
  },

  /**
   * 格式化时间
   */
  formatTime: function (date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();

    return [year, month, day].map(this.formatNumber).join('/') + ' ' + [hour, minute, second].map(this.formatNumber).join(':');
  },

  formatNumber: function (n) {
    n = n.toString();
    return n[1] ? n : '0' + n;
  },

  /**
   * 保存当前AI聊天消息
   */
  saveCurrentAIChatMessages: function () {
    try {
      const key = `ai_chat_${this.data.questionId}`;
      wx.setStorageSync(key, this.data.messages);
    } catch (e) {
      console.error('保存AI聊天消息失败:', e);
    }
  },

  /**
   * 隐藏AI解析
   */
  hideAiAnalysis: function () {
    this.setData({
      showAiAnalysis: false
    });
  },

  /**
   * 判断多选题选项是否正确
   */
  isOptionCorrect: function (correctAnswer, optionId) {
    if (!correctAnswer || !optionId) return false;

    // 将正确答案字符串转换为数组
    const correctIds = correctAnswer.split(',');

    // 检查选项ID是否在正确答案数组中
    return correctIds.includes(optionId);
  },

  /**
   * 获取多选题正确答案的文本显示
   */
  getCorrectAnswerText: function (correctAnswer, options) {
    if (!correctAnswer || !options) return '';

    // 将正确答案字符串转换为数组
    const correctIds = correctAnswer.split(',');

    // 根据选项ID查找对应的选项内容
    const correctOptions = correctIds.map(id => {
      const option = options.find(opt => opt.id === id);
      return option ? option.content : id;
    });

    // 返回格式化的正确答案文本
    return correctOptions.join('、');
  },

  /**
   * 提交多选题答案
   */
  tijiao: function () {
    const currentIndex = this.data.currentQuestionIndex;
    const currentQuestion = this.data.questionBank[currentIndex];

    // 检查当前题目是否为多选题
    if (!currentQuestion || currentQuestion.questionType !== 2) {
      return;
    }

    // 获取用户选择的选项
    const selectedOptions = this.data.selectedOptions[currentIndex] || [];

    // 判断用户是否选择了选项
    if (selectedOptions.length === 0) {
      wx.showToast({
        title: '请至少选择一个选项',
        icon: 'none'
      });
      return;
    }

    // 排序选中的选项，确保与正确答案格式一致
    selectedOptions.sort();

    // 转换正确答案为数组并排序
    const correctAnswers = currentQuestion.correctAnswer.split(',').sort();

    // 判断是否所有选项都正确且数量一致
    let isCorrect = true;
    if (selectedOptions.length === correctAnswers.length) {
      for (let i = 0; i < selectedOptions.length; i++) {
        if (selectedOptions[i] !== correctAnswers[i]) {
          isCorrect = false;
          break;
        }
      }
    } else {
      isCorrect = false;
    }

    // 标记为已回答
    const newAnsweredStatus = { ...this.data.answeredStatus };
    const newCorrectStatus = { ...this.data.correctStatus };
    newAnsweredStatus[currentIndex] = true;
    newCorrectStatus[currentIndex] = isCorrect;

    // 更新selectedClass以显示正确答案和错误答案的样式
    const newSelectedClass = { ...this.data.selectedClass };
    const selectedOption = this.data.selectedOptions[currentIndex] ? this.data.selectedOptions[currentIndex][0] : null;
    const userSelectedOptions = this.data.selectedOptions[currentIndex] || [];
    const userAnswer = userSelectedOptions.join(',');
    const isAnswered = true;
    const questionTypeCode = currentQuestion.questionType;
    const options = currentQuestion.options;

    newSelectedClass[currentIndex] = this.updateSelectedClass(selectedOption, userSelectedOptions, userAnswer, isAnswered, questionTypeCode, options, currentQuestion.correctAnswer);

    this.setData({
      answeredStatus: newAnsweredStatus,
      correctStatus: newCorrectStatus,
      selectedClass: newSelectedClass
    });

    // 显示答题结果提示
    if (isCorrect) {
      // wx.showToast({
      //   title: '回答正确！',
      //   icon: 'success',
      //   duration: 1500
      // });
      this.setData({
        showmsg: true,
        type: 'yes',
        massges: "回答正确！",
      });
      setTimeout(() => {
        this.setData({
          showmsg: false,
          type: '',
          massges: "",
        });
      }, 1000);
    } else {
      // wx.showToast({
      //   title: '回答错误',
      //   icon: 'none',
      //   duration: 1500
      // });
      this.setData({
        showmsg: true,
        type: 'no',
        massges: "回答错误",
      });
      setTimeout(() => {
        this.setData({
          showmsg: false,
          type: '',
          massges: "",
        });
      }, 1000);
    }
  }
});